import { ref } from "vue";
import { defineStore } from "pinia";
import axios from "axios";
import Cookie from "js-cookie";
import router from "@/router/index";
import { toTree, getRoute } from "@/router/permissionRoute";
import { ElMessage } from 'element-plus'

export const useMenuStore = defineStore(
  "menus",
  () => {
    let menusList = ref([]);
    // 获取menu数据
    const getMenus = async () => {
      let id = Cookie.get("id");
      if (id) {
        const {
          data: { data },
        } = await axios.get("/api/routes", {
          params: { id },
        });
        menusList.value = data;
        registerRoute(menusList.value);
      }
    };
    // 注册route
    const registerRoute = (menus) => {
      let data = toTree(menus);
      const pr = getRoute(router.getRoutes(), data);
      router.addRoute(pr);
    };
    // 退出登录
    const logout = () => {
      Cookie.remove("name");
      Cookie.remove("id");
      Cookie.remove("token");
      menusList.value = [];
      localStorage.clear();
      ElMessage.success("成功退出登录");
      setTimeout(() => {
        router.push("/login");
      }, 1000);
    };
    return { menusList, getMenus, logout, registerRoute };
  },
  {
    persist: {
      storage: localStorage,
      paths: ["menusList"],
    },
  }
);
